import React, {useEffect, useRef, useState} from 'react';
import {useLocation} from 'umi';
import {delayStat} from '@/services/delay-stat-api'
import {ProCard, ProFormDateTimeRangePicker, QueryFilter} from "@ant-design/pro-components";
import moment from "moment";
import {Line} from "@ant-design/plots";
import {Datum} from "@ant-design/plots/es/interface";
import {Col, Row, Statistic} from "antd";


function getRandomInRange<T extends number>(min: T, max: T): T {
  return Math.round((Math.random() * (max - min) + min) * 10) / 10 as T;
}

export type TableStatProps = {
  pipelineId?:number;
}

const TableStat: React.FC<TableStatProps> = ( props) => {

  const formRef = useRef();
  const [tableCountStat, setTableCountStat] = useState<any[]>();
  const [tableAvgStat, setTableAvgStat] = useState<any[]>();
  const [tableStat, setTableStat] = useState<API.TableStatDTO>();
  const location = useLocation();
  // @ts-ignore
  const pipelineId = props?.pipelineId || location?.state?.pipelineId || null;

  const transformValue = (data: API.TableStatDTO) => {
    if (data){
      setTableStat(data);
    }
    // 时段内总数
    const tableCountStat = data?.behaviourHistoryInfos
      ?.entries()
      ?.map(([k, v]) => {
        const time = moment(k).format('HH:mm:ss');
        return [
          {x: time, value: v?.insertNumber, category: '插入总数'},
          {x: time, value: v?.updateNumber, category: '更新总数'},
          {x: time, value: v?.deleteNumber, category: '删除总数'},
          {x: time, value: v?.fileNumber, category: '文件数'},
          {x: time, value: v?.fileSize, category: '文件大小'},
        ];
      })
      ?.toArray();

    if (tableCountStat) {
      setTableCountStat(tableCountStat.flat())
    }
    // 时段内平均数
    const tableAvgStat = data?.behaviourHistoryInfos
      ?.entries()
      ?.map(([k, v]) => {
        const time = moment(k).format('HH:mm:ss');
        return [
          {x: time, value: v?.insertCountAvg, category: '平均插入总数'},
          {x: time, value: v?.updateCountAvg, category: '平均更新总数'},
          {x: time, value: v?.deleteCountAvg, category: '平均删除总数'},
          {x: time, value: v?.fileCountAvg, category: '平均文件数'},
          {x: time, value: v?.fileSizeAvg, category: '平均文件大小'},
        ];
      })
      ?.toArray();
    if (tableAvgStat) {
      setTableAvgStat(tableAvgStat.flat())
    }
  }

  useEffect(() => {
    let test = new Array(10);
    let size = new Array(10);
    // TODO 待删除
    let curTime = 1730035307731;
    for (let i = 0; i < 10; i++) {
      curTime = curTime + 60 * 1000 * i;
      test[i] = [
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '插入总数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '更新总数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '删除总数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '文件数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '文件大小'},
      ]
      size[i] = [
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '平均插入总数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '平均更新总数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '平均删除总数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '平均文件数'},
        {x: moment(curTime).format('HH:mm:ss'), value: getRandomInRange(1000, 9999), category: '平均文件大小'},
      ];
    }
    setTableCountStat(test.flat())
    setTableAvgStat(size.flat())
  }, [])

  const queryDelayStat = async (values: any) => {
    let data: API.TableStatDTO = await delayStat({pipelineId: pipelineId, ...values});
    transformValue(data);
  }


  const TableStatLine = (data: { data: Datum }) => {
    const config = {
      data: data.data,
      xField: 'x',
      yField: 'value',
      sizeField: 'value',
      shapeField: 'trail',
      legend: {size: false},
      colorField: 'category',
    };
    return <Line {...config} />;
  };

  return (
      <ProCard direction="column" ghost gutter={[0, 16]}>
        <ProCard>
          <QueryFilter formRef={formRef} onFinish={queryDelayStat} span={12} split>
            <ProFormDateTimeRangePicker
              name={["startTime", "endTime"]}
              fieldProps={{format: 'YYYY-MM-DD HH:mm'}}
              transform={values => values ? {
                startTime: moment(values[0]).valueOf(),
                endTime: moment(values[1]).valueOf()
              } : null}
              label="时间区间"
            />
          </QueryFilter>
        </ProCard>
        <ProCard tabs={{type: 'line'}}>
          <ProCard.TabPane key="count" tab="时段内总数">
            <Row>
              <Col md={3} sm={3} xs={3}>
                <Statistic title="插入总数" value={tableStat?.totalInsert || 0}/>
              </Col>
              <Col md={3} sm={3} xs={3}>
                <Statistic title="更新总数" value={tableStat?.totalUpdate || 0}/>
              </Col>
              <Col md={3} sm={3} xs={3}>
                <Statistic title="删除总数" value={tableStat?.totalDelete || 0}/>
              </Col>
              <Col md={3} sm={3} xs={3}>
                <Statistic title="文件总数" value={tableStat?.totalFileCount || 0}/>
              </Col>
              <Col md={3} sm={3} xs={3}>
                <Statistic title="文件大小" value={tableStat?.totalFileSize || 0}/>
              </Col>
            </Row>
            <TableStatLine data={tableCountStat}/>
          </ProCard.TabPane>
          <ProCard.TabPane key="avg" tab="时段内平均数">
            <TableStatLine data={tableAvgStat}/>
          </ProCard.TabPane>
        </ProCard>
      </ProCard>
  );
};

export default TableStat;
